<template>
  <div class="conf-wrap company-conf">
    <el-row :gutter="10">
      <!-- 左侧面板：企业信息配置 -->
      <el-col :xs="12" :sm="6" :md="6" :lg="5" :xl="4">
        <el-card class="box-card" :body-style="boxCardStyle">
          <div slot="header" class="clearfix">
            <span>企业信息配置</span>
          </div>
          <!-- 企业信息表单 -->
          <el-form ref="companyForm" :model="compForm" label-width="90px" class="wrap-content">
            <el-form-item label="企业名称">
              <el-input v-model="compForm.name" />
            </el-form-item>
            <el-form-item label="企业LOGO">
              <el-upload
                class="avatar-uploader"
                action="not"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-change="handleChange"
              >
                <div class="avatar-preview">
                  <img v-if="compForm.pictureurl" :src="preStr + compForm.pictureurl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </div>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
            <el-form-item class="clearfix">
              <el-button type="primary" plain class="primary-btn-style" @click="handleSaveCompany('companyForm')">保存</el-button>
            </el-form-item>
          </el-form>
          <!-- 制程等四级select -->
          <el-form ref="selectForm" :model="selectForm" label-width="90px" class="wrap-content">
            <el-form-item label="制程管理" prop="process" class="plus-wrap">
              <el-select v-model="selectForm.process" filterable clearable placeholder="请选择" default-first-option @change="handleProcssName">
                <el-option v-for="(item) in processList" :key="item.name+item.id" :label="item.name" :value="item.id" />
              </el-select>
              <el-tooltip class="item" effect="light" content="新增制程" placement="right">
                <el-button type="primary" plain class="primary-btn-style batch-add-btn" icon="el-icon-plus" @click="handleProcessAdd" />
              </el-tooltip>
            </el-form-item>
            <el-form-item label="线别管理" prop="line" class="plus-wrap">
              <el-select v-model="selectForm.line" filterable placeholder="请选择" default-first-option @change="handleLineName">
                <el-option v-for="(item) in lineList" :key="item.name+item.id" :label="item.name" :value="item.id" />
              </el-select>
              <el-tooltip v-show="showLineBtn" class="item" effect="dark" content="新增线别" placement="right">
                <el-button type="primary" plain class="primary-btn-style batch-add-btn" icon="el-icon-plus" @click="handleLineAdd" />
              </el-tooltip>
            </el-form-item>
            <el-form-item label="槽/段管理" prop="slot" class="plus-wrap">
              <el-select v-model="selectForm.slot" filterable placeholder="请选择" default-first-option @change="handleSlotName">
                <el-option v-for="(item) in slotList" :key="item.name+item.id" :label="item.name" :value="item.id" />
              </el-select>
              <el-tooltip v-show="showSlotBtn" class="item" effect="dark" content="新增槽/段" placement="right">
                <el-button type="primary" plain class="primary-btn-style batch-add-btn" icon="el-icon-plus" @click="handleSlotAdd" />
              </el-tooltip>
            </el-form-item>
            <el-form-item label="仪表管理" prop="device" class="plus-wrap">
              <!-- <el-select v-model="selectForm.device" filterable placeholder="请选择" default-first-option>
                <el-option v-for="(item) in deviceList" :key="item.devId" :label="item.devName" :value="item.devId" />
              </el-select> -->
              <el-tooltip class="item" effect="dark" content="请先选择制程、线别、槽/段" placement="right">
                <el-button type="primary" plain class="primary-btn-style batch-add-btn" icon="el-icon-plus" style="width:100%;height:36px;" @click="handleDeviceAdd" />
              </el-tooltip>
            </el-form-item>
            <!-- <el-form-item class="clearfix">
              <el-button type="primary" plain class="primary-btn-style" @click="handleSaveDevForm('selectForm')">保存</el-button>
            </el-form-item> -->
          </el-form>
        </el-card>
      </el-col>
      <!-- 右侧面板：效果预览 -->
      <el-col :xs="12" :sm="18" :md="18" :lg="19" :xl="20">
        <el-card class="box-card" :body-style="{ height: 'calc(100% - 40px)' }">
          <div slot="header" class="clearfix">
            <span>配置预览</span>
          </div>
          <div class="preview-pad">
            <!-- <div class="navbar">
              <company-logo class="company-info" :logo-url="compForm.pictureurl" :company-name="compForm.name" />
              <right-menu />
            </div>
            <dashboard-title :title="title" /> -->
            <section>
              <div v-for="item in totalAllList" :key="item.id" class="custom-tree-container"> <!-- :class="{'new-add-tree': item[0].isCurrent}" -->
                <div class="block">
                  <el-tree
                    :data="item"
                    node-key="id"
                    default-expand-all
                    :props="defaultProps"
                    :expand-on-click-node="false"
                  >
                    <span slot-scope="{ node, data }" class="custom-tree-node">
                      <!-- 编辑状态 -->
                      <template v-if="node.isEdit">
                        <el-input
                          :ref="'slotTreeInput'+data.id"
                          v-model="data.label"
                          autofocus
                          size="small "
                          :placeholder="data.name"
                          @blur.stop="handleInput(node, data, item[0])"
                          @keyup.enter.native="handleInput(node, data, item[0])"
                        />
                      </template>
                      <template v-else>
                        <span>{{ node.label }}</span>
                        <span>
                          <el-button type="text" icon="el-icon-edit" title="编辑" @click="() => editNode(node, data)" />
                          <el-button type="text" icon="el-icon-delete" title="删除" @click="() => removeNode(node, data)" />
                        </span>
                      </template>
                    </span>
                  </el-tree>
                </div>
                <!-- <el-button type="primary" plain class="primary-btn-style">保存</el-button> -->
              </div>
            </section>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增制程弹窗 -->
    <el-dialog
      title="新增制程"
      :visible.sync="processDialogVisible"
      :close-on-click-modal="false"
      append-to-body
      :destroy-on-close="true"
      @close="cancelForm('process')"
    >
      <el-form ref="addProcessForm" :model="newProcessList" label-position="left" label-width="90px" class="dialog-form">
        <el-form-item
          v-for="process in processList"
          :key="process.id"
          label="制程名称"
          :prop="process.name"
        >
          <el-input v-model="process.name" disabled />
        </el-form-item>
        <el-form-item
          v-for="(process, index) in newProcessList.list"
          :key="'process' + index"
          label="新制程"
          :prop="'list.' + index + '.name'"
          :rules="processRule"
          class="plus-wrap"
        >
          <el-input v-model="process.name" placeholder="请输入" />
          <el-button v-show="index === newProcessList.list.length - 1" icon="el-icon-plus" size="mini" @click.prevent="addEmptyInput('process')" />
          <el-button v-show="newProcessList.list.length > 1" icon="el-icon-minus" size="mini" @click.prevent="removeEmptyInput('process', process.name, 'name')" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancelForm('process')">取 消</el-button>
        <el-button type="primary" @click="addProcess('addProcessForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新增线别弹窗 -->
    <el-dialog
      title="新增线别"
      :visible.sync="lineDialogVisible"
      :close-on-click-modal="false"
      append-to-body
      :destroy-on-close="true"
      @close="cancelForm('line')"
    >
      <el-form ref="addLineForm" :model="newLineList" label-position="left" label-width="90px" class="dialog-form">
        <el-form-item
          v-for="line in lineList"
          :key="line.id"
          label="线别"
          :prop="line.id"
        >
          <el-input v-model="line.name" disabled />
        </el-form-item>
        <el-form-item
          v-for="(line, index) in newLineList.list"
          :key="'line'+index"
          label="新线别"
          :prop="'list.' + index + '.name'"
          :rules="lineRule"
          class="plus-wrap"
        >
          <el-input v-model="line.name" placeholder="请输入" />
          <el-button v-show="index === newLineList.list.length - 1" icon="el-icon-plus" size="mini" @click.prevent="addEmptyInput('line')" />
          <el-button v-show="newLineList.list.length > 1" icon="el-icon-minus" size="mini" @click.prevent="removeEmptyInput('line', line.name, 'name')" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancelForm('line')">取 消</el-button>
        <el-button type="primary" @click="addLine('addLineForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新增槽/段弹窗 -->
    <el-dialog
      title="新增槽/段"
      :visible.sync="slotDialogVisible"
      :close-on-click-modal="false"
      append-to-body
      :destroy-on-close="true"
      @close="cancelForm('slot')"
    >
      <el-form ref="addSlotForm" :model="newSlotList" label-position="left" label-width="90px" class="dialog-form">
        <el-form-item
          v-for="slot in slotList"
          :key="slot.id"
          label="槽/段"
          :prop="slot.id"
        >
          <el-input v-model="slot.name" disabled />
        </el-form-item>
        <el-form-item
          v-for="(slot, index) in newSlotList.list"
          :key="'slot'+index"
          label="槽/段"
          :prop="'list.' + index + '.name'"
          :rules="slotRule"
          class="plus-wrap"
        >
          <el-input v-model="slot.name" placeholder="请输入" />
          <el-button v-show="index === newSlotList.list.length - 1" icon="el-icon-plus" size="mini" @click.prevent="addEmptyInput('slot')" />
          <el-button v-show="newSlotList.list.length > 1" icon="el-icon-minus" size="mini" @click.prevent="removeEmptyInput('slot', slot.name, 'name')" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancelForm('slot')">取 消</el-button>
        <el-button type="primary" @click="addSlot('addSlotForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新增仪表弹窗 -->
    <el-dialog
      title="新增仪表"
      :visible.sync="deviceDialogVisible"
      :close-on-click-modal="false"
      append-to-body
      :destroy-on-close="true"
      @close="cancelForm('device')"
    >
      <el-form ref="addDeviceForm" :inline="true" :model="newDeviceList" label-position="left" label-width="80px" class="dialog-form addDeviceForm">
        <!-- <el-form-item
          v-for="device in deviceList"
          :key="device.id"
          label="仪表"
          :prop="device.id"
        >
          <el-input v-model="device.name" disabled />
        </el-form-item> -->
        <div v-for="(device, index) in newDeviceList.list" :key="'device'+index" class="plus-wrap-inline">
          <el-form-item label="仪表名称" :prop="'list.' + index + '.devName'" :rules="deviceRule">
            <el-input v-model="device.devName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="仪表类型" class="dev-small" :prop="'list.' + index + '.devType'" :rules="requiredRules">
            <el-select v-model="device.devType" clearable placeholder="请选择" default-first-option @change="changeUnit">
              <el-option v-for="(item) in deviceTypeList" :key="item.typeName+item.typeId" :label="item.typeName" :value="item.typeId" />
            </el-select>
          </el-form-item>
          <el-form-item label="读数单位" class="dev-small" :prop="'list.' + index + '.devUnit'" :rules="requiredRules">
            <el-input v-model="device.devUnit" />
          </el-form-item>
          <el-form-item>
            <el-button v-show="index === newDeviceList.list.length - 1" icon="el-icon-plus" size="mini" @click.prevent="addEmptyInput('device')" />
            <el-button v-show="newDeviceList.list.length > 1" icon="el-icon-minus" size="mini" @click.prevent="removeEmptyInput('device', device.devName, 'devName')" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer">
        <el-button @click="cancelForm('device')">取 消</el-button>
        <el-button type="primary" @click="addDevice('addDeviceForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getBase64, arrIndexOf } from '@/utils'
// import CompanyLogo from '@/components/CompanyLogo'
// import DashboardTitle from '@/components/DashboardTitle'
// import RightMenu from '@/components/RightMenu'
import { setCompanyInfo, getProcess, addProcess, updataProcess, deleteProcess, getLineByProcess, addLine, getSlotByLine, updataLine, deleteLine, addSlots,
  getDeviceBySlot, updataSlot, deleteSlot, addDevice, updataDevice, deleteDevice, getAllList } from '@/api/conf'

export default {
  // components: { CompanyLogo, DashboardTitle, RightMenu },
  data() {
    var processNotSame = (rule, value, callback) => {
      const arr1 = this.processList.filter(item => {
        return item.name === value
      })
      const arr2 = this.newProcessList.list.filter(item => {
        return item.name === value
      })
      if (arr1.length > 0) {
        callback(new Error('名称不得重复!'))
      } else if (arr2.length > 1) {
        callback(new Error('名称不得重复!'))
      } else {
        callback()
      }
    }
    var lineNotSame = (rule, value, callback) => {
      const arr1 = this.lineList.filter(item => {
        return item.name === value
      })
      const arr2 = this.newLineList.list.filter(item => {
        return item.name === value
      })
      if (arr1.length > 0) {
        callback(new Error('名称不得重复!'))
      } else if (arr2.length > 1) {
        callback(new Error('名称不得重复!'))
      } else {
        callback()
      }
    }
    var slotNotSame = (rule, value, callback) => {
      const arr1 = this.slotList.filter(item => {
        return item.name === value
      })
      const arr2 = this.newSlotList.list.filter(item => {
        return item.name === value
      })
      if (arr1.length > 0) {
        callback(new Error('名称不得重复!'))
      } else if (arr2.length > 1) {
        callback(new Error('名称不得重复!'))
      } else {
        callback()
      }
    }
    var deviceNotSame = (rule, value, callback) => {
      const arr1 = this.deviceList.filter(item => {
        return item.devName === value
      })
      const arr2 = this.newDeviceList.list.filter(item => {
        return item.devName === value
      })
      if (arr1.length > 0) {
        callback(new Error('名称不得重复!'))
      } else if (arr2.length > 1) {
        callback(new Error('名称不得重复!'))
      } else {
        callback()
      }
    }
    return {
      title: '',
      subTitle: '信息化系统',
      nowTime: new Date(),
      boxCardStyle: {
        'height': 'calc(100% - 40px)',
        'display': 'flex',
        'flex-direction': 'column'
      },
      // logo url拼接
      preStr: 'data:image/jpeg;base64,',
      // 企业信息-表单
      compForm: {
        name: '',
        pictureurl: ''
      },
      // 仪表编辑-表单
      selectForm: {
        process: '',
        line: '',
        slot: '',
        device: ''
      },
      // 四个select 必选校验
      selRules: {
        process: [{ required: true, message: '必选项不能为空', type: 'number' }],
        line: [{ required: true, message: '必选项不能为空' }],
        slot: [{ required: true, message: '必选项不能为空' }],
        device: [{ required: true, message: '必选项不能为空' }]
      },
      showLineBtn: false,
      showSlotBtn: false,
      showDeviceBtn: false,
      // 查询到的制程list
      processList: [],
      lineList: [],
      slotList: [],
      deviceList: [],
      scrollDailogTimer: null,
      // 制程、线、槽、仪表 弹窗是否可见
      processDialogVisible: false,
      lineDialogVisible: false,
      slotDialogVisible: false,
      deviceDialogVisible: false,
      // 制程、线、槽 新增的list
      newProcessList: { list: [{ name: '' }] },
      newLineList: { list: [{ name: '' }] },
      newSlotList: { list: [{ name: '' }] },
      newDeviceList: { list: [{ devName: '', devType: '', devUnit: '' }] },
      //  制程、线、槽、仪表 四级新增 必选校验
      requiredRules: [
        {
          required: true, message: '必填项不能为空', trigger: 'blur'
        }
      ],
      // 新增校验规则
      processRule: [
        { required: true, message: '必填项不能为空' },
        { validator: processNotSame, trigger: 'blur' }
      ],
      lineRule: [
        { required: true, message: '必填项不能为空' },
        { validator: lineNotSame, trigger: 'blur' }
      ],
      slotRule: [
        { required: true, message: '必填项不能为空' },
        { validator: slotNotSame, trigger: 'blur' }
      ],
      deviceRule: [
        { required: true, message: '必填项不能为空' },
        { validator: deviceNotSame, trigger: 'blur' }
      ],
      devTemp: {
        name: '',
        type: '',
        count: ''
      },
      // 仪表类型list
      deviceTypeList: [
        { typeId: '1', typeName: '温度', typeUnit: '°C' },
        { typeId: '2', typeName: '压力', typeUnit: 'Kg/cm²' },
        { typeId: '3', typeName: '流量', typeUnit: 'L/min' },
        { typeId: '4', typeName: '电流', typeUnit: 'A' },
        { typeId: '5', typeName: '线速', typeUnit: 'm/min' },
        { typeId: '6', typeName: '计数', typeUnit: '片' },
        { typeId: '7', typeName: '硫酸', typeUnit: '%' },
        { typeId: '8', typeName: '碳酸钠', typeUnit: '%' },
        { typeId: '9', typeName: '氢氧化钠', typeUnit: '%' },
        { typeId: '10', typeName: '比重', typeUnit: '%' },
        { typeId: '11', typeName: '氯酸钠', typeUnit: '%' },
        { typeId: '12', typeName: '盐酸', typeUnit: 'mol/L' }
      ],
      // 仪表类型单位 键值对
      unitObj: {},
      newAddTree: [],
      newAddTreeTemp: [],
      defaultProps: {
        children: 'list',
        label: 'name',
        id: 'id'
      },
      id: 0,
      totalAllList: [],
      isCurrentTree: false
    }
  },
  created() {
    this.initAll()
  },
  methods: {
    initAll() {
      this.deviceTypeList.forEach(item => {
        this.unitObj[item.typeId] = item.typeUnit
      })
      this.getProcessList()
      this.getTotalAll()
    },
    // logo上传
    handleChange(file, fileList) {
      // console.log(file)
      // this.compForm.pictureurl = URL.createObjectURL(file.raw)
      getBase64(file.raw).then(res => {
        const params = res.split(',')
        if (params.length > 0) {
          var pngBase64 = params[1]
        }
        this.compForm.pictureurl = pngBase64
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt500KB = file.size / 1024 < 500

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 PNG 或 JPG 格式!')
      }
      if (!isLt500KB) {
        this.$message.error('上传头像图片大小不能超过 500KB !')
      }
      return isJPG && isLt500KB
    },
    // 企业信息保存
    handleSaveCompany(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // console.log(this.compForm)
          const compParam = Object.assign({}, this.compForm)
          setCompanyInfo(compParam).then(res => {
            this.$message({
              message: 'success',
              type: 'success'
            })
            // this.$refs[formName].resetFields()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getTotalAll() {
      getAllList().then(res => {
        const data = JSON.parse(JSON.stringify(res.data))
        const temp = []
        data.forEach(process => {
          temp.push([process])
          process['level'] = 'process'
          // process['isCurrent'] = process.name === this.selectForm.process
          process.list.forEach(line => {
            line['level'] = 'line'
            line['regionid'] = process.id
            line.list.forEach(slot => {
              slot['level'] = 'slot'
              slot['regionid'] = process.id
              slot['lineId'] = line.id
              slot.list.forEach(device => {
                device['level'] = 'device'
                device['id'] = device.devId
                device['name'] = device.devName
              })
            })
          })
        })
        this.totalAllList = JSON.parse(JSON.stringify(temp))
      })
    },
    // 左侧4个select的保存按钮
    handleSaveDevForm(formName) {
      // console.log(formName)
      this.getTotalAll()
    },
    // 查制程
    getProcessList() {
      getProcess().then(res => {
        this.processList = res.data.map(item => {
          item.id += ''
          return item
        })
      })
    },
    // 新增制程
    handleProcessAdd() {
      this.processDialogVisible = true
    },
    addProcess(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const param = []
          this.newProcessList.list.forEach(item => {
            param.push(item.name)
          })
          // console.log('新增制程：' + param.join(','))
          addProcess({ name: param.join(',') }).then(res => {
            let type = 'error'
            if (res.code === '000000') {
              this.processDialogVisible = false
              type = 'success'
              this.getProcessList()
              this.getTotalAll()
            }
            this.$message({
              message: res.message,
              type: type
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getLineList() {
      getLineByProcess({ regionid: this.selectForm.process }).then(res => {
        this.lineList = res.data.map(item => {
          item.id += ''
          return item
        })
        console.log(this.lineList)
      })
    },
    // 新增线别
    handleLineAdd() {
      this.lineDialogVisible = true
    },
    addLine(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const param = []
          this.newLineList.list.forEach(item => {
            param.push(item.name)
          })
          // console.log('新增产线：' + param.join(','))
          addLine({ regionid: this.selectForm.process, name: param.join(',') }).then(res => {
            let type = 'error'
            if (res.code === '000000') {
              this.lineDialogVisible = false
              type = 'success'
              // 添加成功后，再次查询
              this.getLineList()
              this.getTotalAll()
            }
            this.$message({
              message: res.message,
              type: type
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getSlotList() {
      getSlotByLine({ lineId: this.selectForm.line }).then(res => {
        this.slotList = res.data.map(item => {
          item.id += ''
          return item
        })
      })
    },
    // 新增槽/段
    handleSlotAdd() {
      this.slotDialogVisible = true
    },
    addSlot(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const param = []
          this.newSlotList.list.forEach(item => {
            param.push(item.name)
          })
          // console.log('新增槽：' + param.join(','))
          addSlots({ lineId: this.selectForm.line, name: param.join(',') }).then(res => {
            let type = 'error'
            if (res.code === '000000') {
              this.slotDialogVisible = false
              type = 'success'
              // 添加成功后，再次查询
              this.getSlotList()
              this.getTotalAll()
            }
            this.$message({
              message: res.message,
              type: type
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getDeviceList() {
      getDeviceBySlot({
        regionid: this.selectForm.process,
        lineId: this.selectForm.line,
        slotId: this.selectForm.slot
      }).then(res => {
        this.deviceList = res.data.map(item => {
          item.id += ''
          return item
        })
      })
    },
    // 新增槽/段
    handleDeviceAdd() {
      this.deviceDialogVisible = this.showDeviceBtn
    },
    addDevice(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.newDeviceList.list.forEach(item => {
            item.regionid = this.selectForm.process
            item.lineId = this.selectForm.line
            item.slotId = this.selectForm.slot
          })
          // console.log(this.newDeviceList.list)
          addDevice(this.newDeviceList.list).then(res => {
            let type = 'error'
            if (res.code === '000000') {
              this.deviceDialogVisible = false
              type = 'success'
              // 添加成功后，再次查询
              this.getDeviceList()
              this.getTotalAll()
            }
            this.$message({
              message: res.message,
              type: type
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 弹窗 取消按钮
    cancelForm(type) {
      switch (type) {
        case 'process':
          this.processDialogVisible = false
          this.newProcessList.list = [{ name: '' }]
          break
        case 'line':
          this.lineDialogVisible = false
          this.newLineList.list = [{ name: '' }]
          break
        case 'slot':
          this.slotDialogVisible = false
          this.newSlotList.list = [{ name: '' }]
          break
        case 'device':
          this.deviceDialogVisible = false
          this.newDeviceList.list = [{ devName: '', devType: '', devUnit: '' }]
          break
      }
    },
    changeUnit(val) {
      this.newDeviceList.list.forEach(item => {
        item.devUnit = this.unitObj[item.devType]
      })
    },
    /* 在各新增弹窗中，增加空input
    {param: {string} str : 哪个弹窗}
    */
    addEmptyInput(str) {
      switch (str) {
        case 'process':
          this.newProcessList.list.push({ name: '' })
          break
        case 'line':
          this.newLineList.list.push({ name: '' })
          break
        case 'slot':
          this.newSlotList.list.push({ name: '' })
          break
        case 'device':
          this.newDeviceList.list.push({ devName: '', devType: '', devUnit: '' })
          break
      }
    },
    /* 在各新增弹窗中，删除空input
      {param: {string} str : 哪个弹窗}
      {param: {string} val : 输入的值}
      {param: {string} prop : 属性名}
    */
    removeEmptyInput(str, val, prop) {
      switch (str) {
        case 'process': {
          const idx = arrIndexOf(val, this.newProcessList.list, prop)
          if (idx !== -1) {
            this.newProcessList.list.splice(idx, 1)
          }
          break
        }
        case 'line': {
          const idx = arrIndexOf(val, this.newLineList.list, prop)
          if (idx !== -1) {
            this.newLineList.list.splice(idx, 1)
          }
          break
        }
        case 'slot': {
          const idx = arrIndexOf(val, this.newSlotList.list, prop)
          if (idx !== -1) {
            this.newSlotList.list.splice(idx, 1)
          }
          break
        }
        case 'device': {
          const idx = arrIndexOf(val, this.newDeviceList.list, prop)
          if (idx !== -1) {
            this.newDeviceList.list.splice(idx, 1)
          }
          break
        }
      }
    },
    // 点击 tree 编辑节点按钮，显示输入框
    editNode(_node, _data) {
      // console.log(_data)
      // 设置编辑状态
      if (!_node.isEdit) {
        this.$set(_node, 'isEdit', true)
      }

      // 输入框聚焦
      this.$nextTick(() => {
        // console.log(this.$refs['slotTreeInput' + _data.id])
        if (this.$refs['slotTreeInput' + _data.id]) {
          this.$refs['slotTreeInput' + _data.id][0].$refs.input.focus()
        }
      })
    },
    // 修改节点后的保存
    handleInput(node, data, item) {
      if (!(data.label === undefined || data.label === '' || data.label === data.name)) { // 未输入or非空值or新旧值相同
        if (this.validateNodeChange(data, data.level, item)) {
          switch (data.level) {
            case 'process': {
              updataProcess({
                id: data.id,
                name: data.label
              }).then(res => {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                })
                this.getProcessList()
                this.getTotalAll()
              })
              break
            }
            case 'line': {
              updataLine({
                regionid: data.regionid,
                id: data.id,
                name: data.label
              }).then(res => {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                })
                this.getTotalAll()
              })
              break
            }
            case 'slot': {
              updataSlot({
                regionid: data.regionid,
                lineId: data.lineId,
                id: data.id,
                name: data.label
              }).then(res => {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                })
                this.getTotalAll()
              })
              break
            }
            case 'device': {
              updataDevice({
                regionid: data.regionid,
                lineId: data.lineId,
                slotId: data.slotId,
                devId: data.id,
                devName: data.label
              }).then(res => {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                })
                this.getTotalAll()
              })
              break
            }
          }
        } else {
          this.$message({
            type: 'error',
            message: '名称不得重复'
          })
        }
      } else {
        if (node.isEdit) {
          this.$set(node, 'isEdit', false)
        }
      }
    },
    // 删除节点
    removeNode(_node, _data) {
      if (_data.children && _data.children.length !== 0) {
        this.$message.error('此节点有子级，不可直接删除！')
        return false
      } else {
        this.$confirm('确定删除该节点吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          switch (_data.level) {
            case 'process': {
              deleteProcess({
                id: _data.id
              }).then(res => {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                this.getProcessList()
                this.getTotalAll()
              })
              break
            }
            case 'line': {
              deleteLine({
                regionid: _data.regionid,
                id: _data.id
              }).then(res => {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                this.getLineList()
                this.getTotalAll()
              })
              break
            }
            case 'slot': {
              deleteSlot({
                regionid: _data.regionid,
                lineId: _data.lineId,
                id: _data.id
              }).then(res => {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                this.getSlotList()
                this.getTotalAll()
              })
              break
            }
            case 'device': {
              deleteDevice({
                regionid: _data.regionid,
                lineId: _data.lineId,
                slotId: _data.slotId,
                devId: _data.id
              }).then(res => {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                this.getDeviceList()
                this.getTotalAll()
              })
              break
            }
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    // 编辑节点名称时 非重复值判断
    validateNodeChange(_data, level, item) {
      let flag = false
      switch (level) {
        case 'process':
          flag = arrIndexOf(_data.label, this.processList, 'name') === -1
          break
        case 'line':
          flag = arrIndexOf(_data.label, item.list, 'name') === -1
          break
        case 'slot': {
          const arr = item.list.filter(val => { return val.id === _data.lineId })[0].list
          flag = arrIndexOf(_data.label, arr, 'name') === -1
          break
        }
        case 'device': {
          const arr = item.list.filter(val => { return val.id === _data.lineId })[0].list
          const arr1 = arr.filter(val => { return val.id === _data.slotId })[0].list
          flag = arrIndexOf(_data.label, arr1, 'devName') === -1
          break
        }
      }
      return flag
    },
    // 预览完成后保存
    // handleImport() {
    // },
    // 创建制程
    handleProcssName(val) {
      // this.newAddTreeTemp = []
      // val 为选中的值
      this.showLineBtn = val !== ''
      if (val !== '') {
        this.getLineList()
      }
      this.selectForm.line = ''
      // 高亮选中的制程tree
      // this.totalAllList.forEach(item => {
      //   item[0].isCurrent = item[0].id === parseInt(val)
      // })

      // const selected = this.processList.filter(item => {
      //   return item.id === val
      // })
      // console.log(selected.length)
      // if (selected.length > 0) {
      //   // val为已存在的条目
      //   this.title = selected[0].name + this.subTitle
      // } else if (selected.length === 0) {
      //   this.viewName = val
      //   // val为新创建的条目
      //   this.title = val + this.subTitle

      //   // 预览新tree
      //   this.selectForm.process = val
      //   const item = { id: val, name: val, children: [] }
      //   this.createProcss(item)
      //   this.newAddTreeTemp.push(item)
      // }
    },
    // 创建线别
    handleLineName(val) {
      // val 为选中的值
      this.showSlotBtn = val !== ''
      if (val !== '') {
        this.getSlotList()
      }
      this.selectForm.slot = ''
      // const selected = this.lineList.filter(item => {
      //   return item.id === val
      // })
      // if (selected.length === 0) {
      //   // val为新创建的条目
      //   this.selectForm.line = val
      //   // 预览新tree
      //   const item = { id: val, name: val, children: [] }
      //   this.createLine(item)
      //   this.newAddTreeTemp.forEach(process => {
      //     if (this.selectForm.process === process.id) {
      //       process.children.push(item)
      //       return
      //     }
      //   })
      // }
    },
    // 创建槽位
    handleSlotName(val) {
      // val 为选中的值
      this.showDeviceBtn = val !== ''
      if (val !== '') {
        this.getDeviceList()
      }
      this.selectForm.device = ''
      // const selected = this.slotList.filter(item => {
      //   return item.id === val
      // })
      // if (selected.length === 0) {
      //   // val为新创建的条目
      //   this.selectForm.slot = val
      //   // 预览新tree
      //   const item = { id: val, name: val, children: [] }
      //   this.createSlot(item)
      //   this.newAddTreeTemp.forEach(process => {
      //     if (this.selectForm.process === process.id) {
      //       process.children.forEach(line => {
      //         if (this.selectForm.line === line.id) {
      //           line.children.push(item)
      //           return
      //         }
      //       })
      //       return
      //     }
      //   })
      // }
    },
    // 创建仪表
    handleDevName(val) {
      // val 为选中的值
      console.log(val)
      // const selected = this.deviceList.filter(item => {
      //   return item.id === val
      // })
      // if (selected.length === 0) {
      //   // val为新创建的条目
      //   this.selectForm.device = val
      //   // 预览新tree
      //   const item = { id: val, name: val, children: [] }
      //   this.createSlot(item)
      //   this.newAddTreeTemp.forEach(process => {
      //     if (this.selectForm.process === process.id) {
      //       process.children.forEach(line => {
      //         if (this.selectForm.line === line.id) {
      //           line.children.forEach(slot => {
      //             if (this.selectForm.slot === slot.id) {
      //               slot.children.push(item)
      //               return
      //             }
      //           })
      //           return
      //         }
      //       })
      //       return
      //     }
      //   })
      // }
    }
  }
}
</script>
<style lang="scss">
@import "~@/styles/variables.scss";

.conf-wrap, .el-row, .el-col, .el-card{
    height: 100%;
}
// .bottom{
//     padding: 5px 10px;
    button.primary-btn-style{
        float: right;
        color: #f1f1f1;
        background-color: rgba(63,81,181,.3);
        border-color: $borderColor;
    }
// }
.el-button--text{
    color: #dedede;
}
.el-button--text:hover, .el-button--text:focus{
    color: #fff;
}
.el-card .el-card__body{
  padding: 0;
}
.plus-wrap .el-form-item__content{
  display: flex;
}
.plus-wrap-inline{
  // display: flex;
  .dev-small .el-form-item__content{
    width: 105px;
  }
  .el-form-item:last-child{
        margin-right: 0;
  }
}
.el-tree-node__content{
  height: 32px;
}

.el-dialog__body {
  .el-form{
    height: 100%;
    max-height: 560px;
    overflow: auto
  }
}
</style>
<style lang="scss" scoped>
@import "~@/styles/variables.scss";
$avatarSize: 80px;
$avatarIconSize: $avatarSize - 20px;
.plus-wrap .el-button,
.plus-wrap-inline .el-button{
  margin-left: 0;
}
.wrap-content{
  padding: 10px 10px 0 10px;
  overflow: auto;

  &:nth-child(1){
    border-bottom: $boxBorder;
    margin-bottom: 5px;
  }
}

.batch-add-btn{
    padding: 4px;
    margin-left: 2px;
}

.avatar-preview {
    width: $avatarSize;
    height: $avatarSize;
    padding: 10px;
    display: block;
}
  .avatar-uploader .el-upload {
    border: 1px dashed #5967a4;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    // 减去的是padding
    width: $avatarIconSize;
    height: $avatarIconSize;
    line-height: $avatarIconSize;
    text-align: center;
  }
  .avatar {
    width: 100%;
    display: block;
  }
  .el-upload__tip {
    line-height: 1.5;
  }
  .preview-pad{
    // position: relative;
    // padding: 0;
    height: 100%;

    section{
        display: flex;
        // margin-top: 50px;
        // height: calc(100% - 100px);
        height: 100%;
        overflow-x: auto;
        .custom-tree-container{
            min-width: 250px;
            margin: 5px;
            border: $boxBorder;
            .block{
                  display: block;
                  height: 100%; // calc(100% - 45px)
                  margin-bottom: 5px;
                  overflow: auto;
                p {
                    margin: 5px 0;
                    font-size: 14px;
                    text-indent: 10px;
                }
                //  custom-tree-node ; 是树状结构每个节点的删改按钮
                .custom-tree-node {
                    flex: 1;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    font-size: 14px;
                    padding-right: 8px;
                }
            }
            .primary-btn-style{
              margin-right: 5px;
            }
        }
    }
  }
.new-add-tree {
  border-color: $orange !important;
// .block  .el-tree{
      // color: $tiffany;
  // }
}
//   @media (max-width: 992px) {
//     .avatar-preview {
//         width: 100px;
//         height: 100px;
//     }
//     .avatar-uploader-icon{
//         width: 80px;
//         height: 80px;
//         line-height: 80px;
//     }
// }
</style>
